package com.resou.reader.mine;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.sdk.android.feedback.impl.FeedbackAPI;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DecodeFormat;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.resou.reader.MainActivity;
import com.resou.reader.R;
import com.resou.reader.ReSouApplication;
import com.resou.reader.api.ApiConstant;
import com.resou.reader.api.entry.LoginData;
import com.resou.reader.api.entry.LoginResult;
import com.resou.reader.assist.WebActivity;
import com.resou.reader.base.ResouBaseFragment;
import com.resou.reader.bookshelf.readhistory.ReadHistoryActivity;
import com.resou.reader.mine.IView.UserInstance;
import com.resou.reader.mine.listener.LoginListener;
import com.resou.reader.mine.login.FavoriteActivity;
import com.resou.reader.mine.login.LoginActivity;
import com.resou.reader.mine.login.LoginFragment;
import com.resou.reader.mine.mybooklist.MyBookListActivity;
import com.resou.reader.mine.paycenter.PayCenterActivity;
import com.resou.reader.mine.setting.SettingActivity;
import com.resou.reader.mine.userinfo.UserInfoActivity;
import com.resou.reader.mine.vipcenter.vipCenter.VipCenter;
import com.resou.reader.paycenter.WalletActivity;
import com.resou.reader.test.SignInTestActivity;
import com.resou.reader.utils.ErrorUtils;
import com.resou.reader.utils.PreferenceUtil;
import com.resou.reader.utils.StatusBarUtil;
import com.resou.reader.utils.ViewSizeUtils;
import com.resou.reader.utils.eventbus.LogoutEvent;
import com.resou.reader.utils.eventbus.MessageEvent;
import com.resou.reader.utils.eventbus.UpdateUserIconEvent;
import com.resou.reader.utils.log.LogUtil;
import com.resou.reader.view.CircleImageView;
import com.resou.reader.view.Loading;
import com.resou.reader.view.RowView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.raphets.roundimageview.RoundImageView;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * 我的模块
 */
public class HomeUserCenterFragment extends ResouBaseFragment<HomeUserCenterPresenter> implements IHomeUserCenterInterface.IHomeUserCenterView {
    private static final String TAG = "HomeUserCenterFragment";
    @BindView(R.id.mSmartRefreshLayout)
    SmartRefreshLayout mSmartRefreshLayout;
    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.ivBack)
    ImageView ivBack;
    @BindView(R.id.ivVip)
    ImageView ivVip;
    @BindView(R.id.rlLogined)
    RelativeLayout rlLogined;
    @BindView(R.id.rlLook)
    RelativeLayout rlLook;
    @BindView(R.id.iv_user_head)
    RoundImageView mHeadIv;
    @BindView(R.id.tv_user_name)
    TextView mNameTv;
    @BindView(R.id.tvHotMoney)
    TextView tvHotMoney;
    @BindView(R.id.tvHotTicket)
    TextView tvHotTicket;
    @BindView(R.id.rvVipCenter)
    RowView rvVipCenter;
    @BindView(R.id.ivPic)
    RoundImageView ivPic;
    @BindView(R.id.mTitleBar)
    RelativeLayout mTitleBar;

    Unbinder unbinder;
    private MainActivity mMainActivity;

    AlertDialog.Builder builder = null;
    AlertDialog dialog = null;
    TextUtils tvProgress;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_home_user_center;
    }

    @Override
    protected void initView() {
        // 和顶部保持一定的距离
        int height = ViewSizeUtils.getStatusBarHeight(mActivity.getResources()) + mMainActivity.getState();
        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) mTitleBar.getLayoutParams();
        layoutParams.setMargins(0, height - 10, 0, 0);
        mTitleBar.setLayoutParams(layoutParams);
        mTitleBar.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark));

        mSmartRefreshLayout.setEnablePureScrollMode(true);
        mSmartRefreshLayout.setEnableLoadMore(false);
        mSmartRefreshLayout.setEnableOverScrollDrag(true);
        mSmartRefreshLayout.setEnableOverScrollBounce(true);
        mSmartRefreshLayout.setEnableFooterTranslationContent(true);
        StatusBarUtil.setStatusBarColor(mActivity, getResources().getColor(R.color.color_eeeeee));
        initUserInfo(UserInstance.getLoginData());
        setUserIcon();
        EventBus.getDefault().register(this);
    }

    private void setUserIcon() {
        if (UserInstance.isLogin()) {
            LoginData loginData = UserInstance.getLoginData();
            // 头像
            if (loginData.getHead_pic() != null) {
                RequestOptions options = new RequestOptions()
                        .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                        .format(DecodeFormat.PREFER_RGB_565);
                Glide.with(this).load(loginData.getHead_pic()).apply(options).into(ivPic);
            } else {
                Glide.with(this).load(R.mipmap.user_head).into(ivPic);
            }
        }
    }

    @Override
    protected void retryRefreshData() {

    }


    @Override
    protected void initPresenter() {
        if (mPresenter == null) {
            mPresenter = new HomeUserCenterPresenter(this);
            if (PreferenceUtil.getInstance(ReSouApplication.getRSApplication()).getIsUpdateApp()) {
                mPresenter.updataVersion();
            }
        }
    }

    @Override
    public void initData() {
        tvTitle.setText("我的");
        ivBack.setVisibility(View.GONE);
        if (mMainActivity != null) {
            mMainActivity.initData();
        }
    }

    @Override
    public void initUserInfo(LoginData loginData) {
        if (mPresenter == null) {
            initPresenter();
        }
        mPresenter.initUserInfo(loginData, mHeadIv, mNameTv, tvHotTicket, tvHotMoney);
    }

    @Override
    public void showContent() {

    }

    @Override
    public void showProgress() {

    }

    @Override
    public void showError(Throwable throwable) {

    }

    @Override
    public void showEmpty() {

    }

//
//    @Override
//    public void onSuccess(LoginResult<LoginData> result) {
//        Loading.getInstance().dismiss();
//        LoginFragment.getInstance().dismiss();
//    }

    /**
     * 当用户登录后，更新用户信息
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        Loading.getInstance().dismiss();
        //初始化登录信息
        initUserInfo(UserInstance.getLoginData());
        updataView(!UserInstance.isTourist());
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        unbinder.unbind();
    }
//
//    @Override
//    public void onError(Throwable e) {
//        ErrorUtils.showError(e);
//    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mMainActivity = (MainActivity) context;
    }


    /**
     * 用户是否登录
     *
     * @return
     */
    @Override
    public boolean isAlreadyLogin() {
        return mPresenter.isAlreadyLogin(getFragmentManager());
    }

    @Override
    public void updataView(boolean islogin) {
        mPresenter.updataView(islogin, rlLogined, rlLook);
    }

    @Override
    public void showUpdata(String url) {
        mPresenter.showUpdataDialog(dialog, builder, url);
    }

    @Override
    public void userVipState(boolean isVip) {
        if (UserInstance.getLoginData().getVipEndTime() == null || UserInstance.getLoginData().getVipEndTime().equals("0")) {
            ivVip.setVisibility(View.GONE);
        } else {
            ivVip.setVisibility(View.VISIBLE);
            if (isVip) {
                ivVip.setImageResource(R.mipmap.ic_vip_iconed);
            } else {
                ivVip.setImageResource(R.mipmap.ic_vip_icon);
            }
        }
    }

    @Override
    public void InstallApk(String downloadApk) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        File file = new File(downloadApk);
        LogUtil.d(TAG, "安装路径==" + downloadApk);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Uri apkUri = FileProvider.getUriForFile(getActivity(), "com.resou.reader.fileprovider", file);
//            Uri apkUri = FileProvider.getUriForFile(getActivity(),
//                    SystemUtil.getPackageName(getActivity()) + ".fileprovider", file);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Uri uri = Uri.fromFile(file);
            intent.setDataAndType(uri, "application/vnd.android.package-archive");
        }
        startActivity(intent);
    }


    @Override
    public HomeUserCenterFragment getContent() {
        return this;
    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        if (!hidden) {
            if (1 == UserInstance.getLoginData().getIsVipUser()) {
                userVipState(true);
            } else {
                userVipState(false);
            }
            if (mMainActivity.currentIndex == 3) {
                System.out.println("class:" + this.getClass().getName() + "\thidden:" + hidden);
                StatusBarUtil.setStatusBarColor(mActivity, getResources().getColor(R.color.colorPrimaryDark));
            }
            ((MainActivity) mActivity).initData();
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        onHiddenChanged(false);
    }


    @OnClick({R.id.rlLogined, R.id.user_wallet_layout, R.id.rvVipCenter, R.id.rvreader_track, R.id.rvBookList,
            R.id.rvFavorite, R.id.rvMyNew, R.id.rvSetting, R.id.rvCallMe, R.id.rvHelpCenter, R.id.rvFeedBack, R.id.tv_pay,
            R.id.tvSign, R.id.user_do_task, R.id.rlGoLogin, R.id.ivPic})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ivPic:
                UserInfoActivity.start(mActivity);
                break;
            case R.id.rlGoLogin:
                LoginActivity.start(getActivity());
                break;
            case R.id.rlLogined:
                // start 用户设置页
                UserInfoActivity.start(mActivity);
                break;

            case R.id.user_wallet_layout:
                WalletActivity.startActivity(getActivity());
                // 用户钱包
                break;
            case R.id.rvVipCenter:
                // 会员中心
                VipCenter.start(mActivity);
                break;
            case R.id.user_do_task:
            case R.id.tvSign:   //签到做任务
                WebActivity.startActivity(getActivity(), ApiConstant.VIPDUIBA + UserInstance.getToken(), "签到");

                break;
            case R.id.rvreader_track:
                // 阅读足迹
                ReadHistoryActivity.start(mActivity);
                break;
            //我的书单
            case R.id.rvBookList:
                MyBookListActivity.start(getActivity());
                break;
            case R.id.rvFavorite:
                // 我的喜好
                FavoriteActivity.startActivity(mActivity);
                break;
            case R.id.rvMyNew:
                // 我的消息
                break;
            case R.id.rvSetting:
                // 设置
                SettingActivity.startActivity(mActivity);
                break;
            case R.id.rvCallMe:
                // 联系我们
                WebActivity.startActivity(mActivity, "http://m.resouxs.com/connect?app=app", getResources().getString(R.string.call_me));
                break;
            case R.id.rvHelpCenter:
                WebActivity.startActivity(mActivity, "https://m.resouxs.com/user/helpCenter?app=app", getResources().getString(R.string.help));
                break;
            case R.id.rvFeedBack:
                String nickname = UserInstance.getLoginData().getNickName();
                if (!TextUtils.isEmpty(nickname)) {
                    FeedbackAPI.setUserNick(nickname);
                }
                FeedbackAPI.setActivityCallback(activity -> {
                });
                FeedbackAPI.openFeedbackActivity();
                break;
            case R.id.tv_pay:
                // 充值
                if (isAlreadyLogin()) {
                    startActivity(new Intent(mActivity, PayCenterActivity.class));
                }
                break;
            default:
                break;
        }
    }

    /**
     * 用户修改头像后同步刷新
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(UpdateUserIconEvent event) {
        Loading.getInstance().dismiss();
        if (PreferenceUtil.getInstance(getContext()).getUserIcon() != null) {
            ivPic.setImageURI(Uri.parse(PreferenceUtil.getInstance(getContext()).getUserIcon()));
        }
    }

    /**
     * 用户修改头像后同步刷新
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(LogoutEvent event) {
        Loading.getInstance().dismiss();
        setUserIcon();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
            savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }
}